<template>
  <div>
    <div class="content"
      v-for="(item, index) of arr" :key="item.id">
      <div class="top"
        @touchstart="touchS"
        @touchmove="touchM"
        @touchend="touchE"
        :style="item.style"
        :data-index="index">
        {{item.txt}}
      </div>
      <div class="bottom" @tap="tapDel(index)">
        del
      </div>
    </div>
  </div>
</template>

<script>

export default {
  
  data () {
    return {
      arr: [
        { id: 0, txt: "top0", style: '' },
        { id: 1, txt: "top1", style: '' },
        { id: 2, txt: "top2", style: '' },
        { id: 3, txt: "top3", style: '' },
        { id: 4, txt: "top4", style: '' },
        { id: 5, txt: "top5", style: '' },
        { id: 6, txt: "top6", style: '' },
      ],
      // 按钮宽度
      delWidth: 200,
      // startX
      startX: null,
    }
  },
  methods: {
    // del
    tapDel (index) {
      console.log('del')
      this.arr[index].style = 'left: 0'
      this.arr.splice(index, 1)
      wx.showToast({
        title: 'del' + index, //提示的内容,
        icon: 'none', //图标,
      });
    },
    // start
    touchS (e) {
      // console.log(e.touches[0].clientX)
      if (e.touches.length == 1) {
        this.startX = e.touches[0].clientX
      }
    },
    // move
    touchM (e) {
      // console.log(e)
      if (e.touches.length == 1) {
        // 移动时的实时位置x
        let moveX = e.touches[0].clientX
        // 与初始位置的x距离
        let distX = this.startX - moveX
        // 按钮宽度
        let delW = this.delWidth
        // 实时样式
        var txtStyle = ''
        if (distX == 0 || distX < 0) {
          txtStyle = "left: 0rpx"
        } else if (distX > 0) {
          txtStyle = "left: -" + distX + "rpx"
        } else if (distX > delW) {
          txtStyle = "left: 200rpx"
        }
      }
      let index = e.target.dataset.index
      // console.log(this.arr, index, txtStyle)
      this.arr[index].style = txtStyle
    },
    // end
    touchE (e) {
      // console.log(e)
      if (e.mp.changedTouches.length == 1) {
        // 结束位置
        let endX = e.mp.changedTouches[0].clientX
        let distX = this.startX - endX
        let delW = this.delWidth
        var txtStyle = distX > delW/2 ? "left: -" + delW + "rpx" : "left: 0"
        let index = e.target.dataset.index
        this.arr[index].style = txtStyle
      }

    },
  }
}
</script>

<style lang="scss" scoped>
.content {
  margin: 5rpx;
  position: relative;
  height: 200rpx;
  color: blue;
  background-color: #ddd;
  .top {
    position: absolute;
    z-index: 2;
    width: 100%;
    height: 100%;
    background-color: yellow;
    opacity: 0.8;
    transition: left 0.2s ease-in-out;
  }
  .bottom {
    width: 200rpx;
    height: 100%;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: red;
  }
}
</style>
